package com.ruoyi.web.controller.example;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.resturant.domain.ResShop;
import com.ruoyi.resturant.service.IResShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Anonymous
@Api(tags="Redis测试")
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private IResShopService resShopService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 通过店铺ID取得店铺对象后，把店铺对象存到Redis数据库中
     *
     * @param id 店铺ID
     * @return
     */
    @ApiOperation("存储Redis数据")
    @ApiImplicitParam(name = "id", value = "店铺ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/{id}")
    public AjaxResult setRedisObj(@PathVariable("id") long id){
        //1 通过店铺ID取得店铺对象
        ResShop resShop = resShopService.selectResShopById(id);

        //2 把店铺对象存到Redis中
        String str = JSON.toJSONString(resShop);
        redisCache.setCacheObject(String.valueOf(id), str, 1, TimeUnit.HOURS);

        //3 把店铺对象返回给前端
        return AjaxResult.success(resShop);
    }
    /**
     * 通过店铺ID取得店铺对象
     *
     * @param id 店铺ID
     * @return
     */
    @ApiOperation("取Redis数据")
    @ApiImplicitParam(name = "id", value = "店铺ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/ids/{id}")
    public AjaxResult getRedisObj(@PathVariable("id") Long id) {
        //1根据店铺ID从Redis数据库中取得该店铺的json字符串
        String str = redisCache.getCacheObject(String.valueOf(id));
        //2该店铺的json字符串转换成店铺对象ResShop
        ResShop resShop = JSON.parseObject(str, ResShop.class);
        //3该对象ResShop返回前端
        return AjaxResult.success(resShop);

    }
}